<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @row-save="rowSave"
      @on-load="onLoad"
    >
      <template slot-scope="scope" slot="menu">
        <el-button
          icon="el-icon-view"
          size="small"
          type="text"
          @click.stop="handleView(scope.row, scope.index)"
          >查看</el-button
        >
      </template>
      <template slot="menuLeft">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click.stop="handleSave"
          >新建分账项目</el-button
        >
      </template>
      <template slot-scope="{}" slot="projectCodeSearch">
        <select-page
          ref="searchProjectSelect"
          label="projectName"
          value="projectCode"
          :select.sync="search.projectCode"
          :url="'division/division_project/pageList'"
          placeholder-text="项目"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="aisleCodeSearch">
        <select-page
          ref="searchAisSelect"
          label="aisleName"
          value="aisleCode"
          :select.sync="search.aisleCode"
          :url="'aisle/rbp_pay_aisle/page'"
          placeholder-text="通道"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{ row }" slot="aisleCode">
        <span>{{ row.aisleName }}</span>
      </template>
      <template slot-scope="{ row }" slot="divisionKind">
        <span>{{ row.divisionKindName }}</span>
      </template>
    </avue-crud>

    <!-- 表单弹窗 -->
    <el-dialog
      class="el-dialog__wrapper avue-dialog avue-crud__dialog"
      :title="dialogText"
      :visible.sync="dialogVisible"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form
        ref="form"
        :model="projectForm"
        :rules="rules"
        size="small"
        label-width="120px"
      >
        <div class="haryuki-form-title haryuki-m-b-10 haryuki-m-t-20">
          项目信息
        </div>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="分账项目名称" prop="projectName">
              <el-input
                v-model="projectForm.projectName"
                placeholder="请输入分账项目名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通道简称" prop="aisleKind">
              <select-dict
                ref="aisleKind"
                :select.sync="projectForm.aisleKind"
                code="rbp_aisle_kind"
                placeholder-text="通道简称"
              ></select-dict>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通道名称" prop="aisleCode">
              <select-page
                ref="searchAisSelect"
                label="aisleName"
                value="aisleCode"
                :select.sync="projectForm.aisleCode"
                :url="'aisle/rbp_pay_aisle/page'"
                placeholder-text="通道名称"
                filter-key="searchParam"
              ></select-page>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通道商名称" prop="aisleCompanyCode">
              <select-dict
                ref="aisleCompanyCode"
                :select.sync="projectForm.aisleCompanyCode"
                code="rbp_aisle_company"
                placeholder-text="通道商名称"
              ></select-dict>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分账种类" prop="divisionKind">
              <select-dict
                ref="divisionKind"
                :select.sync="projectForm.divisionKind"
                code="division_kind"
                placeholder-text="分账种类"
              ></select-dict>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="haryuki-form-title haryuki-m-b-10 haryuki-m-t-20">
          联系信息
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input
                v-model="projectForm.contactName"
                placeholder="请输入联系人"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input
                v-model="projectForm.contactPhone"
                placeholder="请输入联系方式"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="haryuki-form-title haryuki-m-b-10 haryuki-m-t-20">
          登录信息
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="登录账户" prop="account">
              <el-input
                v-model="projectForm.account"
                placeholder="请输入登录账户"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录密码" prop="password">
              <el-input
                v-model="projectForm.password"
                type="password"
                placeholder="请输入登录密码"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重复登录密码" prop="confirmPassword">
              <el-input
                v-model="projectForm.confirmPassword"
                type="password"
                placeholder="请再次输入登录密码"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="avue-dialog__footer avue-dialog__footer--right">
        <el-button size="small" type="primary" v-preventClick @click="handleSubmit"
          >确 定</el-button
        >
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  add,
} from "@/api/rb-oem/separateProject/separate_project";
import { mapGetters } from "vuex";
import selectPage from "@/components/select-page/select-page";
import selectDict from "@/components/select-dict/select-dict";

export default {
  name: "SeparateProject",
  components: {
    selectPage,
    selectDict,
  },
  data() {
    // 密码验证规则
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.projectForm.confirmPassword !== "") {
          this.$refs.form.validateField("confirmPassword");
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.projectForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      search: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(100vh - 200px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120,
        searchLabelWidth: 120,
        menuWidth: 150,
        emptyBtnText: "重置",
        column: [
          {
            label: "项目编号",
            searchLabel: "项目名称",
            prop: "projectCode",
            type: "select",
            search: true,
            searchOrder: 4,
            overHidden: true,
            rules: [
              {
                required: true,
                message: "请选择服务商",
                trigger: "blur",
              },
            ],
          },
          {
            label: "项目名称",
            prop: "projectName",
          },
          {
            label: "通道简称",
            prop: "aisleKind",
            type: "select",
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=rbp_aisle_kind",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
          },
          {
            label: "通道名称",
            prop: "aisleCode",
            type: "select",
            props: {
              label: "aisleName",
              value: "aisleCode",
            },
            display: false,
            search: true,
            clearable: true,
            rules: [
              {
                required: true,
                message: "请选择通道名称",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "通道商名称",
            prop: "aisleCompanyName",
          },
          {
            label: "分账种类",
            prop: "divisionKind",
            search: true,
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=division_kind",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
          },
          {
            label: "联系人",
            prop: "contactName",
            search: true,
          },
          {
            label: "联系方式",
            prop: "contactPhone",
            search: true,
          },
          {
            label: "创建日期",
            prop: "createTime",
            type: "input",
            overHidden: true,
          },
          {
            label: "创建日期",
            prop: "timeData",
            type: "datetimerange",
            searchRange: true,
            defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            startPlaceholder: "开始时间",
            endPlaceholder: "截至时间",
            search: true,
            rules: [
              {
                required: true,
                message: "请选择创建日期",
                trigger: "blur",
              },
            ],
            hide: true,
            display: false,
          },
        ],
      },
      data: [],
      dialogVisible: false,
      dialogType: "",
      dialogText: "新建分账项目",
      projectForm: {
        projectName: "",
        aisleCode: "",
        aisleCompanyCode: "",
        aisleKind: "",
        divisionKind: "",
        contactName: "",
        contactPhone: "",
        account: "",
        password: "",
        confirmPassword: "",
      },
      rules: {
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        aisleCode: [
          { required: true, message: "请选择通道名称", trigger: "change" },
        ],
        aisleKind: [
          { required: true, message: "请选择通道简称", trigger: "change" },
        ],
        aisleCompanyCode: [
          { required: true, message: "请选择通道商", trigger: "change" },
        ],
        divisionKind: [
          { required: true, message: "请选择分账种类", trigger: "change" },
        ],
        contactName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        contactPhone: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        account: [
          { required: true, message: "请输入登录账户", trigger: "blur" },
        ],
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.separate_project_add, false),
        viewBtn: this.vaildData(this.permission.separate_project_view, false),
        editBtn: this.vaildData(this.permission.separate_project_edit, false),
      };
    },
  },
  watch: {
    "search.timeData"(val) {
      if (val) {
        this.search.createTimeStart = val[0];
        this.search.createTimeEnd = val[1];
      } else {
        this.search.createTimeEnd = "";
        this.search.createTimeStart = "";
      }
    },
  },
  methods: {
    searchReset() {
      this.query = {};
      this.search = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    sortChange(val) {
      if (val.order == "ascending") {
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleSave() {
      this.dialogVisible = true;
      this.dialogType = "add";
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      });
    },
    handleView(row) {
      this.$router.push({
        name: "分账项目详情",
        query: {
          d: this.$crypto.encrypt(
            JSON.stringify({
              projectCode: row.projectCode,
            })
          ),
        },
      });
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "提交中...",
            spinner: "el-icon-loading",
          });
          add(this.projectForm)
            .then(() => {
              this.$message.success("操作成功");
              this.dialogVisible = false;
              this.refreshChange();
            })
            .finally(() => {
              loading.close();
            });
        }
      });
    },
    handleClose(done) {
      this.$refs.form.resetFields();
      done();
    },
  },
};
</script>

<style lang="scss" scoped>
.separate-project {
  /deep/ .el-tag--dark.el-tag--success {
    border: none !important;
  }
}

.haryuki-form-title {
  font-weight: bold;
  text-align: center;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 10px;
}

.haryuki-m-b-10 {
  margin-bottom: 10px;
}
</style>